package com.paradise.sharding.eth.controller;


import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.paradise.sharding.eth.entity.EthTransaction;
import com.paradise.sharding.eth.service.EthTransactionServiceImpl;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * ETH区块交易表 前端控制器
 * </p>
 *
 * @author Paradise
 * @since 2021-07-15
 */
@Slf4j
@RestController
@RequestMapping("/eth/transaction")
@AllArgsConstructor
public class EthTransactionController {

    private final EthTransactionServiceImpl transactionService;

    @PostMapping
    @ApiOperation("新增")
    public ResponseEntity<EthTransaction> insert(@RequestBody EthTransaction transaction) {
        final boolean res = transactionService.save(transaction);
        if (res) {
            return ResponseEntity.ok(transaction);
        }
        return ResponseEntity.internalServerError().build();
    }

    @GetMapping
    @ApiOperation("查询")
    public ResponseEntity<List<EthTransaction>> query(@RequestParam(required = false) String from,
                                                      @RequestParam(required = false) Long startBlockNumber,
                                                      @RequestParam(required = false) Long endBlockNumber,
                                                      @RequestParam(required = false) Long blockNumber,
                                                      @RequestParam(required = false) String to) {
        final LambdaQueryChainWrapper<EthTransaction> wrapper = transactionService.lambdaQuery();
        wrapper.eq(StringUtils.isNotEmpty(from), EthTransaction::getFrom, from);
        wrapper.eq(StringUtils.isNotEmpty(to), EthTransaction::getTo, to);
        wrapper.eq(blockNumber != null, EthTransaction::getBlockNumber, blockNumber);
        wrapper.ge(startBlockNumber != null, EthTransaction::getBlockNumber, startBlockNumber);
        wrapper.le(endBlockNumber != null, EthTransaction::getBlockNumber, endBlockNumber);
        wrapper.gt(EthTransaction::getValue, new BigDecimal("50000000000000000"));
        final Integer count = wrapper.count();
        log.info("count : {} ", count);

        final long l1 = System.currentTimeMillis();
        final List<EthTransaction> list = wrapper.list();
        log.info("查询数据：{}", list.size());
        log.info("查询耗时：{}ms", System.currentTimeMillis() - l1);
        return ResponseEntity.ok(list.subList(0, Math.min(count, 10)));
    }

}

